//
//  HMSportCameraController.m
//  HMSport
//
//  Created by apple on 2017/4/26.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMSportCameraController.h"
#import <AVFoundation/AVFoundation.h>

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

@interface HMSportCameraController ()
@property (strong, nonatomic) IBOutletCollection(NSLayoutConstraint) NSArray *cameraConstraints;

//输入设备
@property (nonatomic, strong) AVCaptureDeviceInput *input;
//输出设备
@property (nonatomic, strong) AVCaptureStillImageOutput *output;
//会话
@property (nonatomic, strong) AVCaptureSession *session;
//预览视图layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
//相机预览视图
@property (weak, nonatomic) IBOutlet UIView *cameraView;
//对调摄像头按钮
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;
//距离文本水印
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
//运动图片水印
@property (weak, nonatomic) IBOutlet UIImageView *sportImgV;
//图片保存文本
@property (weak, nonatomic) IBOutlet UILabel *imgSaveLabel;
//相机按钮
@property (weak, nonatomic) IBOutlet UIButton *cameraBtn;
//保存的图片
@property (nonatomic, strong) UIImage *savedImg;

@end

@implementation HMSportCameraController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //设置相机
    [self setupCamera];
    //设置距离水印内容
    self.distanceLabel.text = [NSString stringWithFormat:@"%.2f km", self.track.totalDistance];
}


//设置相机
- (void)setupCamera{

    //输入设备 摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //输出设备
    self.output = [[AVCaptureStillImageOutput alloc] init];
    //会话
    self.session = [[AVCaptureSession alloc] init];
    //添加输入/输出设备
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.output]) {
        [self.session addOutput:self.output];
    }
    
    //预览视图layer
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
 
    [self.cameraView.layer insertSublayer:self.previewLayer atIndex:0];
    
    //设置视频预览样式  如果不设置就会按照设备的尺寸按比例缩放
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //开始会话
    [self.session startRunning];
}

//拍照
- (void)takePicture{
    //执行拍照
    [self.output captureStillImageAsynchronouslyFromConnection:self.output.connections.firstObject completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        //图片数据采样缓冲区  包含图像信息
        
//        NSLog(@"%@", imageDataSampleBuffer);
        //获取图片二进制文件
        NSData *data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        
        UIImage *img = [UIImage imageWithData:data];
        
        //对图片进行裁切
        CGFloat offset = ([UIScreen mainScreen].bounds.size.height - self.cameraView.frame.size.height) * 0.5;
        
//        CGRect tarRect = CGRectInset(self.cameraView.frame, 0, -offset);
        
        //创建图片上下文 上下文的尺寸就是最终图片的尺寸  如果希望使用当前设备的分辨率生成图片,需要设置Option中scale属性为0,如果没有设置的话,会使用默认的分辨率(480*320)生成图片
        UIGraphicsBeginImageContextWithOptions(self.cameraView.frame.size, YES, 0);
        //将图片画到上下文  参数设置尺寸是图片在上下文坐标系中的位置
        [img drawInRect:CGRectMake(0, -offset, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; // (0,0, 320, 480)

        //添加文字水印  使用自定义字体使用attributedText来设置
        [self.distanceLabel.attributedText drawInRect:self.distanceLabel.frame];
        
        //添加图片水印
        [self.sportImgV.image drawInRect:self.sportImgV.frame];
        
        //从上下文中获取图片
        UIImage *editedImg = UIGraphicsGetImageFromCurrentImageContext();
        
        //关闭上下文
        UIGraphicsEndImageContext();
        
        //保存到相册  SEL必须使用指定的回调方法
        UIImageWriteToSavedPhotosAlbum(editedImg, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        
        //记录图片
        self.savedImg = editedImg;
    }];
}

//保存图片后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    
    //执行翻转动画
    [self rotateAnim];
    //停止采集
    [self.session stopRunning];
    
    //打开快门
    [self cameraWithClose:NO];

    //设置延迟 等打开快门动画执行到一半时显示文本
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.imgSaveLabel.alpha = 1.0;
        self.imgSaveLabel.text = (error == nil) ? @"图片保存成功": @"图片保存失败";
        //设置动画
        [UIView animateWithDuration:1 animations:^{
            self.imgSaveLabel.alpha = 0;
        }];
    });
}

//可以设置单个控制器不显示状态栏
- (BOOL)prefersStatusBarHidden{

    return YES;
}

- (void)viewDidLayoutSubviews{

    [super viewDidLayoutSubviews];
    self.previewLayer.frame = self.cameraView.bounds;
}

//执行快门操作
- (void)cameraWithClose:(BOOL)close{

    //iOS推荐使用禁用/启用约束的方式来调整视图的约束,而不推荐使用更新/删除约束的方式来调整视图(这种方式性能较差)
    
    if (close) { //关闭快门
        
        //禁用约束
        [NSLayoutConstraint deactivateConstraints:self.cameraConstraints];
        
    }else {
        
        //启用约束
        [NSLayoutConstraint activateConstraints:self.cameraConstraints];
    }
    //设置autolayout动画
    [UIView animateWithDuration:0.5 animations:^{
        
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - 响应事件

//切换摄像头&分享
- (IBAction)clickChangeBtn:(UIButton *)sender {
    
    //判断会话是否正在执行 区分摄像头对调/分享
    if (!self.session.isRunning) {
        
        //分享图片
        [self shareImg];
        return;
    }
    
    //停止采集
    [self.session stopRunning];
    //切换选中状态
    sender.selected = !sender.selected;
    //获取设备
    AVCaptureDevice *device = [self getChangeDevice];
    //会话添加新输入设备前,需要线移除已经添加的输入设备
    [self.session removeInput:self.input];
    //设置输入设备
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //重新关联会话
    if ([self.session canAddInput:self.input]) {
        
        [self.session addInput:self.input];
    }
    //重新采集信息
    [self.session startRunning];
}

//分享图片
- (void)shareImg{

    //1、创建分享参数
    NSArray* imageArray = @[self.savedImg];
    //（注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"分享内容"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        //有的平台要客户端分享需要加此方法，例如微博
        [shareParams SSDKEnableUseClientShare];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
        [ShareSDK showShareActionSheet:nil items:nil shareParams:shareParams onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];}
}

//获取设备
- (AVCaptureDevice *)getChangeDevice{

    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    //选中按钮使用前置,没有选中使用后置
    AVCaptureDevicePosition position = self.changeBtn.selected ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
    
    for (AVCaptureDevice *device in devices) {
        //判断是否为需求的设备
        if (device.position == position) {
            
            return device;
        }
    }
    
    return devices.firstObject;
}


//点击拍照
- (IBAction)clickCameraBtn:(id)sender {
    
    if (self.session.isRunning == NO) { //照片模式
        
        //执行翻转动画
        [self rotateAnim];
        //开始采集
        [self.session startRunning];
        
        return;
    }
    
    //关闭快门
    [self cameraWithClose:YES];
    
    //执行拍照
    [self takePicture];

    

}

//设置翻转动画
- (void)rotateAnim{

    //拍摄状态下点击按钮: 文字从无到有 按钮进行从右向左翻转  切换图片(对调摄像头->分享) 停止采集信息
    //照片状态下点击按钮: 文字从有到无 按钮进行从左向右翻转  切换图片 分享->对调摄像头 开始采集信息
    
    //设置文字
    NSString *title = self.session.isRunning ? @"✓" : nil;
    [self.cameraBtn setTitle:title forState:UIControlStateNormal];
    //设置翻转动画
    UIViewAnimationOptions option = self.session.isRunning ? UIViewAnimationOptionTransitionFlipFromRight : UIViewAnimationOptionTransitionFlipFromLeft;
    [UIView transitionWithView:self.cameraBtn duration:0.5 options: option animations:nil completion:nil];
    [UIView transitionWithView:self.changeBtn duration:0.5 options:option animations:nil completion:nil];
    //切换图片
    NSString *imgName = self.session.isRunning ? @"ic_waterprint_share" : @"ic_waterprint_revolve";
    [self.changeBtn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
}



- (IBAction)clickCloseBtn:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
